package com.dongzili.auth.service;

import com.dongzili.entity.Role;
import com.dongzili.entity.User;
import com.dongzili.data.mybatisplus.MybatisPlusUtil;

import java.util.*;
import java.util.stream.Collectors;

public class UserService {

    public static User getUserById(Integer id){
        User user = MybatisPlusUtil.getMapper(User.class).selectById(id);
        fillUser(user);
        return user;
    }

    /** 填充用户角色信息 */
    public static void fillUser(User user){
        if (user != null){
            if (user.getRoleIds()==null || user.getRoleIds().isEmpty()){
                user.setRoleIds(Collections.singletonList(1001));
            }
            List<Role> roles = MybatisPlusUtil.getMapper(Role.class).selectBatchIds(user.getRoleIds());
            List<String> codes = roles.stream().map(Role::getCode).distinct().collect(Collectors.toList());
            user.setRoles(roles);
            user.setRoleCodes(codes);
        }
    }

    /** 批量填充用户角色信息 */
    public static void fillUsers(List<User> users){
        if (users == null || users.isEmpty()) {
            return;
        }
        Set<Integer> roleIds = users.stream()
                .flatMap(user -> user.getRoleIds().stream())
                .collect(Collectors.toSet());
        roleIds.add(1001);
        Map<Integer, Role> roleMap =MybatisPlusUtil.getMapper(Role.class).selectBatchIds(roleIds).stream().collect(Collectors.toMap(Role::getId, role -> role));
        users.forEach(user -> {
            List<Role> roles = new ArrayList<>();
            List<String> codes = new ArrayList<>();
            if (user.getRoleIds()==null || users.isEmpty()){
                user.setRoleIds(Collections.singletonList(1001));
            }
            for (Integer roleId : user.getRoleIds()) {
                Role role = roleMap.get(roleId);
                if (role != null){
                    roles.add(role);
                    codes.add(role.getCode());
                }
            }
            user.setRoles(roles.stream().distinct().collect(Collectors.toList()));
            user.setRoleCodes(codes);
        });
    }
}
